package com.ruoyi.ade.llm.model;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * 检索到的ADE知识
 */
public class AdeRetrivedKnowledge implements Comparable{

    /**
     * 相似性得分 ：  通常是向量数据库检索到的结果
     */
    private float simScore;
    /**
     * 相关性得分：   通常是rerank计算后的得分
     */
    private float reScore;
    /**
     * 检索到的知识
     */
    private AdeKnowledge knowledge;

    /**
     * 将Milvus中检索到的对象 转换成检索结果对象
     * @param mor
     * @return
     */
    public static AdeRetrivedKnowledge fromMilvusObject(AdeMilvusResponse mor){
        AdeRetrivedKnowledge rak = new AdeRetrivedKnowledge();
        rak.setSimScore(mor.getScore());
        rak.setReScore(0f);
        AdeKnowledge ade = new AdeKnowledge(mor.getId(), mor.getText(), mor.getAde(), mor.getExplain());
        rak.setKnowledge(ade);
        return rak;
    }


    public float getSimScore() {
        return simScore;
    }

    public void setSimScore(float simScore) {
        this.simScore = simScore;
    }

    public float getReScore() {
        return reScore;
    }

    public void setReScore(float reScore) {
        this.reScore = reScore;
    }

    public AdeKnowledge getKnowledge() {
        return knowledge;
    }

    public void setKnowledge(AdeKnowledge knowledge) {
        this.knowledge = knowledge;
    }

    /**
     * 默认根据相似性来排序
     * @param o
     * @return
     */
    @Override
    public int compareTo(@NotNull Object o) {
        AdeRetrivedKnowledge tmp = (AdeRetrivedKnowledge) o;
        return tmp.getSimScore()-this.getSimScore()>0?1:-1;
    }


    /**
     * 将检索到的知识组装成字符串
     *
     * @param ades
     * @return
     */
    public static String formatKnowledge(List<AdeRetrivedKnowledge> ades) {
        if(ades == null || ades.size() == 0) return "";
        StringBuilder sb = new StringBuilder();
        for (AdeRetrivedKnowledge ade : ades) {
            if ("{}".equals(ade.getKnowledge().getAde()) || StringUtils.isEmpty(ade.getKnowledge().getAde()))
                sb.append("“" + ade.getKnowledge().getText() + "”该描述没有药物不良反应因果关系；\n");
            else
                sb.append("“" + ade.getKnowledge().getText() + "”该描述是明确的药物不良反应事件；\n");
        }
        return sb.toString();
    }


    /**
     * 【XXXX】识别结果是：{“sentence":,"durgs":[],"reactions":[]}
     *
     * @param ades
     * @return
     */
    public static String format(List<AdeKnowledge> ades) {
        StringBuilder sb = new StringBuilder();
        int index = 0;
        for (AdeKnowledge ade : ades) {
            index++;
//            if(ade.getAde().getSentence()!=null)
            sb.append("\t\"" + ade.getText() + "\"识别结果：" + JSONObject.toJSONString(ade.getAde()) + "\n");
//            else
//                sb.append("\t\"" + ade.getText() + "\"不是药物不良反应事件\n");
        }
        return sb.toString();
    }
}
